package com.roubsite.admin.dao.rsMenu;

import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.roubsite.admin.bean.MenuTree;
import com.roubsite.admin.bean.RsMenu;
import com.roubsite.database.bean.Record;
import com.roubsite.database.dao.DataSet;
import com.roubsite.database.dao.EntityDao;

public class RsMenuDao extends EntityDao implements IRsMenuDao {

	@Override
	public DataSet getInfoById(String id) {
		DataSet ds = this.queryBean("SELECT * FROM RS_MENU WHERE MENU_ID =?", new String[] { id },
				new int[] { Types.VARCHAR }, false, 0, 0, RsMenu.class);
		return ds;
	}

	@Override
	public DataSet queryd(Record record, int start, int rows) {
		return this.queryBean(record.toBean(RsMenu.class), null, true, start, rows);
	}

	@Override
	public int saveData(Record record, Class<?> bean) {
		return this.save(record, bean);
	}

	@Override
	public int del(List ids) throws Exception {
		String tableName = "RS_MENU";
		String keyField = "MENU_ID";
		StringBuffer delSql = new StringBuffer("DELETE FROM " + tableName + " WHERE " + keyField + " IN (");
		for (int i = 0; i < ids.size(); i++) {
			delSql.append("'");
			delSql.append(ids.get(i));
			delSql.append("',");
		}
		String sql = delSql.substring(0, delSql.length() - 1);
		sql = sql + ")";

		return this.excute(sql, new Object[] {}, new int[] {});
	}

	@Override
	public List<Map<String, Object>> queryAll() {
		return  this.query("SELECT * FROM RS_MENU ORDER BY ORDER_ID ASC", null, null);
	}

	@Override
	public List<MenuTree> getAdminMenu(String parentId, String userId) {
		String sql = "SELECT DISTINCT M.MENU_ID, M.MENU_NAME, M.PARENT_ID, M.MENU_ICON, M.MENU_URL, ORDER_ID FROM RS_MENU M"
				+ "	LEFT JOIN RS_ROLE_MENU RM ON M.MENU_ID = RM.MENU_ID"
				+ "	LEFT JOIN RS_USERS_ROLE UR ON UR.ROLE_ID = RM.ROLE_ID"
				+ "	LEFT JOIN RS_USERS U ON UR.USER_ID = U.USER_ID WHERE U.USER_ID = ? AND M.IS_SHOW = 1 ORDER BY " +
				"ORDER_ID ASC";
		List<Map<String, Object>> menuList = this.query(sql, new String[] { userId }, new int[] { Types.VARCHAR });
		List<MenuTree> reList = new ArrayList<>();
		for (Map<String, Object> map : menuList) {
			Record record = new Record();
			record.fromMap(map);
			RsMenu data = (RsMenu) record.toBean(RsMenu.class);
			MenuTree t = new MenuTree();
			t.setId(data.getMenuId());
			t.setText(data.getMenuName());
			t.setIcon(data.getMenuIcon());
			t.setParentId(data.getParentId());
			t.setUrl(data.getMenuUrl());
			reList.add(t);
		}
		return reList;
	}
}
